<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\XnH5ThirdUser;
use App\Models\XnH5User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class H5UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:h5user', ['except' => ['loginBySms','refresh','me']]);
    }

    public function loginBySms(Request $request) {
        $user = XnH5ThirdUser::query() -> where([
            'phone'     => $request->phone,
            'sms_code'  => $request->sms_code
        ])->first();
        if (!$user) {
            return response()->json(['error' => '验证码错误'], 401);
        }
        if(Carbon::now()->timestamp > $user -> expire_time){
            return response()->json(['error' => '验证码已过期'], 401);
        }
        $token = auth('h5user')->login($user);
        if(!$token){
            return response()->json(['error' => '登录失败'], 401);
        }
        $user -> login_time = Carbon::now();
        $user -> save();
        return successly([
            'access_token' =>$token,
            'token_type' => 'bearer',
            'expires_in'   => auth('h5user')->factory()->getTTL() * 60,
            'userInfo'=>auth('h5user')->user()
        ]);
    }
    public function me()
    {
        return response()->json(auth('h5user')->user());
    }
    public function logout()
    {
        auth('h5user')->logout();
        return response()->json('退出成功');
    }
    public function refresh()
    {
        return response()->json([
            'access_token' =>auth('h5user')->refresh(),
            'token_type' => 'bearer',
            'expires_in'   => auth('h5user')->factory()->getTTL() * 60,
            'userInfo'=>auth('h5user')->user()
        ]);
    }
}
